<template>
	<el-dialog v-model="dialogVisible" :title="title" width="500">
		<main class="content">
			<el-form ref="formRef" :model="formData" :rules="rules" label-width="auto">
				<el-form-item label="项目名称" prop="name">
					<el-input v-model="formData.name" placeholder="请输入项目名称" />
				</el-form-item>
				<el-form-item label="项目编码" prop="code">
					<el-input v-model="formData.code" placeholder="请输入项目编码" />
				</el-form-item>
			</el-form>
		</main>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm(formRef)">
					确定
				</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { addProject, updateProject } from '@/api/projectList';
interface RuleForm {
	_id?: string;
	name: string;
	code: string;
}
interface Props {
	isEdit?: boolean;
	editData?: RuleForm | null;
}


const emit = defineEmits(['save-success'])
const dialogVisible = defineModel();
const props = withDefaults(defineProps<Props>(), {
	isEdit: false,
	editData: null
})
const formRef = ref<FormInstance>();
const formData = ref<RuleForm>({
	name: '',
	code: ''
});
const rules = ref<FormRules<RuleForm>>({
	name: [
		{
			required: true,
			message: '请输入项目名称',
			trigger: 'blur'
		},
	],
	code: [
		{
			required: true,
			message: '请输入项目编码',
			trigger: 'blur',
		},
	]
})
const title = computed(() => props.isEdit ? '编辑项目' : '添加项目')

const setFormData = () => {
	formData.value = {
		name: props.editData?.name || '',
		code: props.editData?.code || ''
	}
}
const submitForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate(valid => {
		if (valid) {
			const api = props.isEdit ? updateProject : addProject;
			if (props.isEdit) {
				formData.value._id = props.editData?._id || '';
			}
			api(formData.value).then(() => {
				dialogVisible.value = false;
				ElMessage.success('添加成功');
				emit('save-success');
			})
		}
	})
}

watch(() => dialogVisible.value, val => {
	if (val) {
		formRef.value && formRef.value.resetFields();
		if (props.isEdit) {
			setFormData()
		}
	}
})
</script>
<style lang='scss' scoped>
.content {
	padding: 16px 20px;
}
</style>
